# -*- coding: utf8-*-



import dateutil, pylab,random
from pylab import *
from datetime import datetime,timedelta
import sys
import os

try:
    my_site = os.path.join(os.environ['HOME'],
                       'Library/Python/2.7/lib/python/site-packages')
    sys.path.insert(0, my_site)
    print sys.path
    reload(matplotlib.pyplot)
except:
    pass

import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.dates as mdate
import matplotlib.ticker as mtick
import numpy as np


from PIL import Image


print plt.__file__

def polyLine(x,y,labelx,labely,pictitle):

    dates = x
    print dates
    # values = [random.randint(1, 20) for i in range(10)]
    values = y
    pylab.plot_date(pylab.date2num(dates), values, linestyle='-')
    #text(17, 277, u'瞬时流量示意')
    xtext = xlabel(labelx)
    ytext = ylabel(labely)
    ttext = title(pictitle)
    grid(False)
    setp(ttext, size='large', color='r')
    # setp(text, size='medium', name='courier', weight='bold',color='b')
    setp(xtext, size='large', name='Arial', weight='bold', color='g')
    setp(ytext, size='large', name='Arial', weight='light', color='b')
    # savefig('simple_plot.png')
    savefig(pictitle,dpi=600)
    show()

def testDraw():
    today = datetime.now()
    dates = [today + timedelta(days=i) for i in range(5)]
    print dates
    # values = [random.randint(1, 20) for i in range(10)]
    values = [3, 2, 8, 4, 5]
    pylab.plot_date(pylab.date2num(dates), values, linestyle='-')
    text(17, 277, u'瞬时流量示意')
    xtext = xlabel(u'时间time (s)')
    ytext = ylabel(u'单位 (m3)')
    ttext = title(u'xx示意图')
    grid(True)
    setp(ttext, size='large', color='r')
    # setp(text, size='medium', name='courier', weight='bold',color='b')
    setp(xtext, size='medium', name='courier', weight='bold', color='g')
    setp(ytext, size='medium', name='helvetica', weight='light', color='b')
    # savefig('simple_plot.png')
    savefig('simple_plot')
    show()




def test3():
    x = [0, 1, 2, 3, 4, 5, 6]
    y = [0.3, 0.4, 2, 5, 3, 4.5, 4]
    fig = plt.figure(figsize=(8, 4))  # 创建绘图对象
    plt.plot(x, y, "b--", linewidth=1)  # 在当前绘图对象绘图（X轴，Y轴，蓝色虚线，线宽度）
    plt.xlabel("Time(s)")  # X轴标签
    plt.ylabel("Volt")  # Y轴标签
    plt.title("Line plot")  # 图标题
    plt.show()  # 显示图
    plt.savefig("line.jpg")  # 保存图
def drawBugTrends(dates1,bugs1,dates2,bugs2,label1,lable2):
    print "date1",dates1,bugs1
    print "date2",dates2,bugs2
    x_date = [datestr2num(i) for i in dates1]
    x_date2 = [datestr2num(i) for i in dates2]
    #plt.style.use('ggplot')
    plt.figure(figsize=(12, 8))
    plt.title("Bug Trend")
    plt.xlabel("Create Date")
    plt.xticks(rotation=45)
    plt.ylabel("Bugs Number")
    plt.plot_date(x_date, bugs1, '-', label=label1)
    plt.plot_date(x_date2, bugs2, '-', label=lable2)
    plt.legend()
    plt.grid(True)
    plt.savefig("bugtrends")

    plt.close()
    convertPngToBmp("bugtrends")
    cropImage("bugtrends.bmp",100,50,1100,800)
def drawBugDistributionPie(lables,fracs,title):
    colorsMap={3:['green', 'red', 'orange'],4: ['green', 'red', 'orange','RosyBrown'],5 :['green', 'red', 'orange','RosyBrown','blue'],6:['green', 'red', 'orange','RosyBrown','blue','purple'],7:['green', 'red', 'orange','RosyBrown','blue','purple','cyan']}
    set_ch()
    labels = lables
    fracs = fracs
    colors = colorsMap[len(fracs)]
    #explode = [0, 0.15, 0]  # 0.1 凸出这部分，
    plt.axes(aspect=1)  # set this , Figure is round, otherwise it is an ellipse
    # autopct ，show percet

    plt.title(title)
    plt.figure(figsize=(5, 3.5))
    wedgeprops = {'linewidth': 1, 'edgecolor': 'white'}
    patches, l_text, p_text = plt.pie(x=fracs, labels=labels,autopct='%3.1f %%', colors=colors,
            shadow=False, labeldistance=1.1, startangle=90, pctdistance=0.6,radius=0.8,wedgeprops=wedgeprops

            )

    for t in l_text:
        t.set_size(10)
    for t in p_text:
        t.set_size(10)
    plt.axis('equal')
    plt.legend(loc='upper left', bbox_to_anchor=(-0.15, 1))
    plt.savefig(title)
    plt.close()
    convertPngToBmp(title)

def convertPngToBmp(pngFile):
    im = Image.open(pngFile+".png")
    im = im.convert("RGB")
    im.save(pngFile+".bmp")

def cropImage(imagefile,x,y,width,height):
    img = Image.open(imagefile)
    region = (x, y, width, height)
    # 裁切图片
    cropImg = img.crop(region)
    # 保存裁切后的图片
    cropImg.save(imagefile)


def drawBar(iosBugs,androidBugs,otherbugs,all_dates):
    n_groups = len(all_dates)

    maxBugsNumber = max(list(set(iosBugs)|set(androidBugs)|set(otherbugs)))
    #means_men = (20, 35, 30, 35, 27)

    #means_women = (25, 32, 34, 0, 25)




    fig, ax = plt.subplots()
    plt.figure(figsize=(6.5, 4))

    index = np.arange(n_groups)

    bar_width = 0.15


    opacity = 0.9
    print index


    rects1 = plt.bar(index, iosBugs, bar_width, alpha=opacity, color='orange', label='IOS Bugs')


    rects2 = plt.bar(index+bar_width, androidBugs, bar_width, alpha=opacity, color='g', label='Android Bugs')


    rects3 = plt.bar(index+bar_width*2, otherbugs, bar_width, alpha=opacity, color='r', label='Other Bugs')





    plt.xlabel('Create Date')

    plt.ylabel('Bug Number')

    plt.title('Bug Trends')

    plt.xticks(index + bar_width, all_dates)

    plt.ylim(0, maxBugsNumber+3)

    plt.legend()


    plt.tight_layout()
    picName = "Bug Trends"
    plt.savefig(picName)
    convertPngToBmp(picName)

def drawBarForPC(pcBugs,all_dates):
    n_groups = len(all_dates)

    maxBugsNumber = max(list(pcBugs))
    #means_men = (20, 35, 30, 35, 27)

    #means_women = (25, 32, 34, 0, 25)




    fig, ax = plt.subplots()
    plt.figure(figsize=(6.5, 4))

    index = np.arange(n_groups)

    bar_width = 0.15


    opacity = 0.9
    print index


    rects1 = plt.bar(index, pcBugs, bar_width, alpha=opacity, color='orange', label='PC Bugs')







    plt.xlabel('Create Date')

    plt.ylabel('Bug Number')

    plt.title('Bug Trends')

    plt.xticks(index, all_dates)

    plt.ylim(0, maxBugsNumber+3)

    plt.legend()


    plt.tight_layout()
    picName = "PCBugs"
    plt.savefig(picName)
    convertPngToBmp(picName)


def set_ch():
	from pylab import mpl
	mpl.rcParams['font.sans-serif'] = ['Arial'] # 指定默认字体
	mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
if __name__ =='__main__':
    x = [0,1,2,3,4,5,6]
    y = [0.3,0.4,2,5,3,4.5,4]
    # polyLine(x, y, "date", "bug")
    drawBar()
